package com.book.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.book.dao.BookImageDao;
import com.book.dto.BookImgPage;
import com.book.entity.BookImage;
import com.book.service.BookImgService;
import com.book.utils.ResponseResult;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 错误码从14001开始
 */
@Service
public class BookImgServiceImpl implements BookImgService {
    @Autowired
    private BookImageDao bookImageDao;

    /**
     * 获取所有的书籍图片信息
     * @param bookImgPage
     * @return
     */
    @Override
    public ResponseResult getBookImg(BookImgPage bookImgPage) {
        try {
            QueryWrapper<BookImage> qw = new QueryWrapper<>();;
            if(bookImgPage.getBookId()!=0){

                qw.eq("book_id",bookImgPage.getBookId());
            }
            qw.orderByDesc("book_id").orderByDesc("id");
            PageHelper.startPage(bookImgPage.getCurrentPage(),bookImgPage.getPageSize());
            List<BookImage> bookImages = bookImageDao.selectList(qw);
            PageInfo<BookImage> bookImagePageInfo = new PageInfo<>(bookImages);

            if(bookImgPage.getCurrentPage()>bookImagePageInfo.getPages()){
                PageHelper.startPage(bookImagePageInfo.getPages(),bookImgPage.getPageSize());
                bookImages = bookImageDao.selectList(qw);
                bookImagePageInfo = new PageInfo<>(bookImages);
            }
            return new ResponseResult(200,"查询书籍图片信息成功",bookImagePageInfo);
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(14001,"查询书籍图片信息失败");
        }
    }


    /**
     * 根据id删除某张图片
     * @param id
     * @return
     */
    @Override
    public ResponseResult deleteImg(int id) {
        try {
            return new ResponseResult(200,"删除图片成功",bookImageDao.deleteById(id));
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(14002,"删除图片失败");
        }
    }


    /**
     * 上传书籍图片后保存书籍图片
     * @param bookId
     * @param imgAdd
     * @return
     */
    @Override
    public ResponseResult saveImg(int bookId, List<String> imgAdd) {
        try {
            for (String imgUrl : imgAdd) {
                BookImage bookImage = new BookImage();
                bookImage.setBookId(bookId);
                bookImage.setImg(imgUrl);
                bookImageDao.insert(bookImage);
            }
            return new ResponseResult(200,"保存图片信息成功");
        }catch (Exception e){
            e.printStackTrace();
            return new ResponseResult(13004,"保存图片信息失败");
        }
    }
}
